layui.use(['dtree'], function(){
  var dtree = layui.dtree;
  var table = layui.table;
  var form = layui.form;
  var lastRoleIdsArr;
  var lastDeptIdsArr;
  var checkUserId;

 
//初始化角色选择下拉框
 initAsynSelect({
	   ele: '#roleSelect'
	  ,url: ctx+"/sys/role/getList"
	  ,value: 'roleId'
	  ,name: 'roleName'
  })

//初始化状态下拉框
$("#userStatusSelect").initSelectDict();
	  
  //部门下拉选择
  var deptTreeSelect = dtree.renderSelect({
	  elem: "#deptTreeSelect",
	  url: ctx+"/sys/dept/getDtreeList",
	  method: "get",
	  dataStyle: "layuiStyle",  
	  dataFormat: "list",  
	  response: {message:"msg",statusCode:200}, 
	  menubar: true, 
	  menubarTips:{
		    group:["moveDown", "moveUp","searchNode", {
		      menubarId: "clearSelectNode",  
		      icon: "dtree-icon-homefill", 
		      title: "初始化",  
		      handler: function(node, $div){ 
		    	  deptTreeSelect.menubarMethod().refreshTree();
		    	  $("#deptId").val("");
		      }
		    }]
		  },
	  selectTips: "请选择部门"
  });
  dtree.on("node('deptTreeSelect')" ,function(obj){
	  $("#deptId").val(obj.param.nodeId)
   });
  $(".dtree-select").css("z-index",999);
  
  //用户管理table
  initTable({
	 elem: '#user-t'
    ,url: ctx+'/sys/user/getPage'
    ,cols: [[
       {field:'userId', title: 'ID', hide: true}
      ,{field:'userCode', minWidth:150, title: '用户编码', sort: true}
      ,{field:'userName', minWidth:150, title: '用户名', sort: true}
      ,{field:'sex', minWidth:80, title: '性别', sort: true
    	  ,templet: function(d){
    		  return transDict("sex",d.sex);
    	  }
      }
      ,{field:'email', width:200, title: '邮箱'}
      ,{field:'phone', width:200, title: '手机'}
      ,{field:'userStatus', minWidth:80, title: '状态'
    	  ,templet: function(d){
    		  return transDict("userStatus",d.userStatus);
    	   }
      }
      ,{
			title: '操作',
			align: 'center',
			minWidth: 180,
			toolbar: '#user-t-tool',
			fixed: 'right'
		}
    ]]
  })
  
  //条件搜索
  $("#userSearch").click(function(){
	    var searchData = $("#userSearchForm").serializeObject();
		layui.table.reload('user-t', {
			where : searchData,
			page : {
				curr : 1
			}
		});
  })
  
  //监听工具条
  table.on('tool(user-t)', function(obj){
    var id = obj.data.userId;
    if(obj.event === 'detail'){
    	var url = ctx+"/sys/user/userDetail?id="+id;
		$.get(url, {}, function(res){
			if(!isJSON(res)){
			  var index = layer.open({
					title: "详情",
					type: 1,
					skin: 'layui-layer-rim', 
					area: ['30%', '70%'],  
					offset: ['5%', '20%'],
			        content: res,
					btn: [],
					end: function(){
						tableReload();
					}
			  		,maxmin: true
			  });
			  layer.full(index);
			}
		  });
		
    } else if(obj.event === 'del'){
      layer.confirm('确定删除吗？', function(index){
    	  ajaxCommit({
    		  url : ctx+"/sys/user/del?id="+id
    		  ,successfunc: function(){ tableReload() }
    	  })
      });
    } else if(obj.event === 'edit'){
		var url = ctx+"/sys/user/editView?id="+id;
		$.get(url, {}, function(res){
			if(!isJSON(res)){
			  var index = layer.open({
					title: "编辑",
					type: 1,
					skin: 'layui-layer-rim', 
					area: ['30%', '70%'],  
					offset: ['5%', '20%'],
			        content: res,
					btn: [],
					end: function(){
						tableReload();
					}
			  		,maxmin: true
			  });
			  layer.full(index);
			}
		  });
    }
  });
  
  //添加按钮
  $("#userAdd").click(function(){
	  var url = ctx+"/sys/user/addView";
	  $.ajax({
		type : 'get',
		url : url,
		data : '',
		success : function(res) {
			if(!isJSON(res)){
				var index = layer.open({
					title: '添加',
					type: 1,
					skin: 'layui-layer-rim', 
					area: ['30%', '70%'],  
					offset: ['5%', '20%'],
					content: res,
					btn: [],
					end: function(){
						tableReload();
					}
					,maxmin: true
				});
				layer.full(index);
			}
		}
	});
	
  })

 
  
  //监听行单击事件
  table.on('row(user-t)', function(obj){
	checkUserId = obj.data.userId;
	obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
		 //点击用户加载角色列表
		 var roleTable = layui.table.render({
  			  elem: '#role-t'
  			 ,url: ctx+ '/sys/user/getUserRole?id='+checkUserId
  			 ,cols: [[
  			       {type:'checkbox'}
  			      ,{field:'roleId', title:'ID', hide:true}
  			      ,{field:'roleName', minWidth:'180', title: '角色名', sort: true}
  			      ,{field:'roleCode', minWidth:'180', title: '角色编码', sort: true}
  			      ,{field:'roleSort', minWidth:'80', title: '等级', sort: true}
  			    ]]
			    ,page: false
			    ,response: {
			      statusCode: 200 
			    }
			  	,parseData: function(res){
			  		return {
				      "code": res.code, 
				      "msg": res.msg, 
				      "data": res.data 
				    };
				} 
			  	,done: function (res, curr, count) {
			  		var lastRoleData =  table.checkStatus('role-t').data;
			  		lastRoleIdsArr = getSplitArr(lastRoleData,'roleId');
			  	}
			  });
		 
		 //点击用户加载部门树
		  var deptTree = dtree.render({
			  elem: "#deptTree",
			  url: ctx+"/sys/user/getUserDept?id="+checkUserId,
			  method: "get",
			  dataStyle: "layuiStyle",  
			  dataFormat: "list",  
			  response:{message:"msg",statusCode:200}, 
			  menubar: true, 
			  checkbar: true, 
			  checkbarType: "all" 
			  ,initLevel: 999
			  ,done: function(data, obj, first){
			    if(first) {
			      $("#deptSearch").unbind("click");
			      $("#deptSearch").click(function(){
			        var value = $("#deptSearchName").val();
			        if(value){
			          var flag = deptTree.searchNode(value); // 内置方法查找节点
			          if (!flag) {layer.msg("该名称节点不存在！", {icon:5});}
			        } else {
			        	deptTree.menubarMethod().refreshTree(); // 内置方法刷新树
			        }
			      });
			      //获取初始选中值
			      var lastDeptData = dtree.getCheckbarNodesParam("deptTree");
			  	  lastDeptIdsArr = getSplitArr(lastDeptData,'nodeId');
			    }
			 }
		  });
		  
		//绑定节点点击事件
		  dtree.on("node(deptTree)", function(obj){
		    if(!obj.param.leaf){
		      var $div = obj.dom;
		      deptTree.clickSpread($div);  
		    } 
		  });
		  
		  $("#deptSearch").click(function(){
			  var input = $("#deptSearchName").val();
			  deptTree.fuzzySearch(input);
		  });
  });
  
  
  $("#saveUserRole").click(function(){
	  if(null==checkUserId || '' == checkUserId){
		  layer.alert("请选择一条用户记录");
		  return false;
	  }
	 var roleData =  table.checkStatus('role-t').data;
	 var roleIdsArr = getSplitArr(roleData,'roleId');
	 var params = {
			  "userId":checkUserId
			 ,"roleIds":roleIdsArr
			 ,"lastRoleIds":lastRoleIdsArr
	 		};
	 ajaxCommit({
    	 url : ctx + "/sys/user/saveUserRole"
    	,data :params
     })
  })
  
  $("#saveUserDept").click(function(){
	  if(null==checkUserId || '' == checkUserId){
		  layer.alert("请选择一条用户记录");
		  return false;
	  }
	  var deptData = dtree.getCheckbarNodesParam("deptTree");
	  var deptIdsArr = getSplitArr(deptData,'nodeId');
	  var params = {
		  "userId":checkUserId
		 ,"deptIds":deptIdsArr
		 ,"lastDeptIds":lastDeptIdsArr
	  };
	  ajaxCommit({
	     url : ctx + "/sys/user/saveUserDept"
	    ,data : params
	  })
  })
  
  $("#resetPwd").click(function(){
	  if(null==checkUserId || '' == checkUserId){
		  layer.alert("请选择一条用户记录");
		  return false;
	  }
	  layer.confirm('确定重置密码吗？', function(index){
		  ajaxCommit({
			  url: ctx + "/sys/user/resetPwd?userId="+checkUserId
		  })
		  
	  })
  });
  
  //下载excel
  $("#export").click(function(){
		var searchData = $(".table-search-form").serializeObject();
		var url = ctx+"/sys/user/export";
		downloadExcel({url:url,data:searchData});
  })
   
  //上传excel
  uploadExcel({
	    elem: '#import'
	   ,url: ctx+"/sys/user/uploadExcel"
	   ,field: 'excelFile'
	   ,successfunc: function(){ tableReload(); }
  });
  
  
});